package com.lagou.module4.servlet;

import com.lagou.module4.model.User;
import com.lagou.module4.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        System.out.println("账号为: "+userName+"密码为："+passWord);

        UserService userService = new UserService();
        User user = userService.userLoginService(new User(userName, passWord));
        if (null == user){
            System.out.println("login failed");
            response.setContentType("text/html;charset=utf-8");
            request.getSession().setAttribute("type","登陆失败");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else {
            System.out.println("login success!");
            response.setContentType("text/html;charset=utf-8");
            request.getSession().setAttribute("type","登陆成功");
            request.getSession().setAttribute("user",user);
            response.sendRedirect("main.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
